import { Component, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeleteResult, Repository } from 'typeorm';
import { ArticleEntity } from './article.entity';

@Component()
export class ArticleService {
  constructor(
    // 定义在当前范围中注册的存储库
    @InjectRepository(ArticleEntity)
    private readonly articleRepository: Repository<ArticleEntity>,
  ) {}

  // 查找所有的文章
  async findAll(): Promise<ArticleEntity[]> {
    return await this.articleRepository.find();
  }

  // 创建文章
  async create(article: ArticleEntity): Promise<ArticleEntity> {
    return await this.articleRepository.save(article);
  }

  // 根据文章的别名更新
  async update(slug: string, articleData: any): Promise<ArticleEntity> {
    // 通过文章别名 查找到对应的文章
    const toUpdate = await this.articleRepository.findOne({ slug: slug });
    // 将后面的对象合并到前面实现更新
    const update = Object.assign(toUpdate, articleData);
    return await this.articleRepository.save(update);
  }

  // 删除文章
  async delete(slug: string): Promise<DeleteResult> {
    return await this.articleRepository.delete({ slug: slug });
  }
}
